package com.millioncool.selfpagingsimple;

import android.app.Application;
import android.os.Handler;
import android.os.Looper;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.alibaba.fastjson.JSONObject;
import com.millioncool.selfpagingsimple.paging.PagingPager;
import com.millioncool.selfpagingsimple.paging.PagingSource;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

/**
 * @Author: QDL
 * @CreateDate: 2021/4/23 14:21
 */
public class MainViewModel extends AndroidViewModel {
    PagingSource<Integer, BaseItemBean> pagingSource;
    int position = 1;
    MutableLiveData<List<BaseItemBean>> pagingLiveData;
    PagingPager<BaseItemBean> pagingPager;

    public MainViewModel(@NonNull Application application) {
        super(application);
    }

    public void init() {
        pagingSource = new PagingSource<Integer, BaseItemBean>(new PagingSource.LoadParams<>(1)) {
            @Override
            public void loadData(LoadParams<Integer> loadParams, ResultCallBack<Integer, BaseItemBean> resultCallBack) {
                Executors.newFixedThreadPool(1).execute(() -> {
                    String response = getRequestJson();
                    JSONObject jsonObject = JSONObject.parseObject(response);
                    List<BaseItemBean> list = new ArrayList<>();
                    if (loadParams == null || loadParams.getKey() == 1) {
                        list.add(new HeaderBean());
                        list.add(new CategoryBean());
                    }
                    list.addAll(JSONObject.parseArray(jsonObject.getString("data"), ItemBean.class));
                    list.add(new NoMoreDataBean());

                    new Handler(Looper.getMainLooper()).post(() -> resultCallBack.onSuccess(loadParams.setKey(loadParams.getKey() + 1), list));
                });
            }
        };

        pagingPager = pagingSource.getPagingPager();
        pagingLiveData = pagingPager.getPagingLiveData();
    }


    /**
     * 模拟数据
     *
     * @return
     */
    public synchronized String getRequestJson() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "success");

        List<BaseItemBean> data = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            data.add(new ItemBean("ITEM" + position));
            position++;
        }

        jsonObject.put("data", data);
        return jsonObject.toJSONString();
    }

}
